﻿using Minio;
using Minio.ApiEndpoints;
using Minio.DataModel.Args;
using Minio.Exceptions;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace MarkDownFileSplitter
{
    public class MinioFileUploader
    {
        // 配置参数 (根据实际环境修改)
        private const string Endpoint = "192.168.2.231:9002";  // MinIO 服务地址
       
        private const string BucketName = "zhishiku"; // 存储桶名称
        private const bool UseSsl = false;                 // 是否启用HTTPS

        public static async Task Upload(string filePath)
        {
            try
            {
                // 初始化客户端
                var minioClient = await InitializeMinioClient();

                // 执行上传
                await UploadFileToMinio(minioClient, filePath);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"上传失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 初始化 MinIO 客户端
        /// </summary>
        private static async Task<IMinioClient> InitializeMinioClient()
        {
            var client = new MinioClient()
                .WithEndpoint(Endpoint)
                .WithCredentials(GlobalSetting.Instance.MinIOAccessKey, GlobalSetting.Instance.MinIOSecretKey)
                .WithSSL(UseSsl)
                .Build();

            // 添加超时处理
            var cts = new CancellationTokenSource();
            cts.CancelAfter(TimeSpan.FromSeconds(30)); // 设置30秒超时

            try
            {
                // 检查存储桶是否存在
                var bucketExistsArgs = new BucketExistsArgs().WithBucket(BucketName);
                bool bucketExists = await client.BucketExistsAsync(bucketExistsArgs, cts.Token);

                if (!bucketExists)
                {
                    var makeBucketArgs = new MakeBucketArgs().WithBucket(BucketName);
                    await client.MakeBucketAsync(makeBucketArgs, cts.Token);
                }
            }
            catch (OperationCanceledException)
            {
                throw new TimeoutException("MinIO 操作超时，请检查网络连接或服务器状态");
            }
            catch (Exception ex)
            {
                throw new Exception($"MinIO 初始化失败: {ex.Message}");
            }

            return client;
        }

        private static async Task btnGetBucketFiles(IMinioClient minioClient, string bucketName)
        {
            try
            {
                var sb = new StringBuilder();
                var bucketExistsArgs = new BucketExistsArgs().WithBucket(bucketName);
                // Just list of objects
                // Check whether 'mybucket' exists or not.
                bool found =await minioClient.BucketExistsAsync(bucketExistsArgs);
                if (found)
                {
                    // List objects from 'my-bucketname'
                    ListObjectsArgs args = new ListObjectsArgs()
                                              .WithBucket(bucketName)
                                              .WithPrefix("prefix")
                                              .WithRecursive(true);
                    var  observable = minioClient.ListObjectsEnumAsync(args);

                    await foreach (var item in observable)
                    {
                        sb.AppendLine($"OnNext: {item.Key}");
                    }
                    
                }
                else
                {
                    Console.WriteLine("mybucket does not exist");
                }
                var cc = sb.ToString();
            }
            catch (MinioException e)
            {
                Console.WriteLine("Error occurred: " + e);
            }

        }

        /// <summary>
        /// 上传文件到 MinIO
        /// </summary>
        private static async Task UploadFileToMinio(IMinioClient client, string filePath)
        {
            // 验证文件是否存在
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException("目标文件不存在", filePath);
            }

            // 生成存储对象名称 (示例：按日期分类)
            string objectName = GenerateObjectName(filePath);

            // 设置上传参数
            var putObjectArgs = new PutObjectArgs()
                .WithBucket(BucketName)
                .WithObject(objectName)
                .WithFileName(filePath)
                .WithContentType("text/markdown");  // 明确 MIME 类型

            await client.PutObjectAsync(putObjectArgs);

            client.Dispose();
        }

        

        /// <summary>
        /// 生成存储对象名称 (可根据需求自定义)
        /// </summary>
        private static string GenerateObjectName(string filePath)
        {
            // 示例：按日期分类存储
            // 格式：YYYY-MM/DD/filename.md
            DateTime now = DateTime.Now;
            return Path.GetFileName(filePath);
        }
    }

    
}